<?php
include __DIR__ . '/alidayu/TopSdk.php';
/**
 * 阿里大鱼短信接口
 */
class Alidayu {
    private $config = [];
    public $error = '';
    /**
     * 阿里大鱼短信接口
     * @param array $config <ul>
     * <li>string $key AppKey </li>
     * <li>string $secret AppSecret </li>
     * <li>string $sign 短信签名 </li>
     * </ul>
     */
    public function __construct(array $config) {
        $this->config = $config;
    }
    
    /**
     * 发送普通短信
     * @param string|array $mobile 
     * @param array $params
     * @return boolean
     */
    public function sendSms($mobile, $params) {
        $sms_id = $params['sms_id'];
        unset($params['sms_id']);
        if (empty($sms_id)) {
            $this->error = "参数有误：sms_id不能为空";
            return false;
        }
        if (empty($mobile)) {
            $this->error = "参数有误：手机号码不能为空";
            return false;
        }
        if (empty($params)) {
            $this->error = "参数有误：短信模板参数不能为空";
            return false;
        }
        if (empty($this->config['key']) || empty($this->config['secret']) || empty($this->config['sign'])) {
            $this->error = "参数有误：阿里大鱼配置信息有误";
            return false;
        }
        if (is_array($mobile)) {
            $mobile = implode(",", $mobile);
        }
        foreach ($params as $key => $value) {
            $params[$key] = (string) $value;
        }
        $c = new \TopClient;
        $c->appkey = trim($this->config['key']);
        $c->secretKey = trim($this->config['secret']);
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        //    $req->setExtend("123456");
        $req->setSmsType("normal");
        $req->setSmsFreeSignName(trim($this->config['sign']));
        $req->setSmsParam(json_encode($params));
        $req->setRecNum($mobile);
        $req->setSmsTemplateCode(trim($sms_id));
        $resp = $c->execute($req);
        $result = $this->simplexml_obj2array($resp);

        if (isset($result['result']) && $result['result']['success'] == 'true') {
            return true;
        } else {
            $error = "";
            foreach ($result as $key => $value) {
                $error .= "{$key}:{$value};";
            }
            $this->error = $error;
            return false;
        }
    }
    
    // XML转换成数组
    private function simplexml_obj2array($obj) {
        if (is_object($obj)) {
            $result = array();
            foreach ((array) $obj as $key => $item) {
                $result[$key] = $this->simplexml_obj2array($item);
            }
            return $result;
        }
        return $obj;
    }

}
